﻿using UnityEditor;
using UnityEngine;

public class CopyUIRelativePath
{
    [MenuItem("Assets/Mini Tools/UI/Copy UI Relative Path", false, 1)]
    [MenuItem("GameObject/Mini Tools/GameObject/Copy UI Relative Path", false, 1)]
    private static void Main()
    {
        if (Selection.activeTransform == null)
        {
            if (Selection.activeObject != null)
            {
                string path = AssetDatabase.GetAssetPath(Selection.activeObject);
                EditorGUIUtility.systemCopyBuffer = path;
                Debug.Log(path);
            }
            return;
        }

        if (Selection.gameObjects.Length == 1)
        {
            var child = Selection.gameObjects[0].transform;
            string path = child.name;

            while (child.parent != null)
            {
                path = child.parent.name + "/" + path;
                child = child.parent;
            }

            EditorGUIUtility.systemCopyBuffer = path;

            Debug.Log(path);
            return;
        }

        if (Selection.gameObjects.Length == 2)
        {
            Transform child = null;
            Transform parent = null;
            bool result = GetPaternity(ref child, ref parent);
            if (result == true)
            {
                string path = child.name;
                while (child.parent != parent)
                {
                    path = child.parent.name + "/" + path;
                    child = child.parent;
                }

                EditorGUIUtility.systemCopyBuffer = path;

                Debug.Log(path);
                return;
            }
            Debug.Log("当前选中的两个对象不存在父子关系");
            EditorGUIUtility.systemCopyBuffer = string.Empty;
            return;
        }

        Debug.Log("当前选中对象过多，不要超过两个对象");
        EditorGUIUtility.systemCopyBuffer = string.Empty;
    }

    private static bool CheckPaternity(Transform child, Transform parent)
    {
        while (child.parent != null)
        {
            if (child.parent == parent)
            {
                return true;
            }
            child = child.parent;
        }
        return false;
    }

    private static bool GetPaternity(ref Transform child, ref Transform parent)
    {
        var t1 = Selection.gameObjects[0].transform;
        var t2 = Selection.gameObjects[1].transform;
        bool result = CheckPaternity(t1, t2);
        if (result == true)
        {
            child = t1;
            parent = t2;
            return true;
        }
        result = CheckPaternity(t2, t1);
        if (result == true)
        {
            child = t2;
            parent = t1;
            return true;
        }
        return false;
    }

}
